#include<iostream>
#include<vector>
#include<queue>
#include<string>
using namespace std;


int perimeter = 0;
vector<vector<bool>> visited;
void dfs(int x,int y,vector<vector<int>> grid)
{   
    if(x<0||y<0||x>grid.size()-1||y>grid[0].size()-1||grid[x][y]==0)
    {
        cout<<"out of bound"<<endl;
        perimeter++;
    }
    if(!visited[x][y])
    {
        visited[x][y]=true;
        if(x<=grid.size()-1)
            dfs(x+1,y,grid);
        if(x>=0)
            dfs(x-1,y,grid);
        if(y<=grid[0].size()-1)
            dfs(x,y+1,grid);
        if(y>=0)
            dfs(x,y-1,grid);
    }
}
int islandPerimeter(vector<vector<int>>& grid) {
    int x=0;
    int y=0;
    while(x<grid.size()&&y<grid[0].size()&&grid[x][y]==1)
    {
        
        if(x!=grid.size()-1)
        {
            x++;
        }
        else
        {
            x=0;
            y++;
        }
    }
    vector<vector<bool>> visited(grid.size(),vector<bool>(grid[0].size()));
    //找到第一个1进行深搜
    dfs(x,y,grid);
    return perimeter;
}
int main()
{
    vector<vector<int>> grid(4);
    cout<<"enter the 2d array"<<endl;
    for(int i=0;i<grid.size();i++)
    {
        for(int j=0;j<5;j++)
        {
            int x;
            cin>>x;
            grid[i].push_back(x);
        }
    }
    cout<<"the 2d array is"<<endl;
    for(int i=0;i<grid.size();i++)
    {
        for(int j=0;j<5;j++)
        {
            cout<<grid[i][j]<<" ";
        }
        cout<<endl;
    }
    int perimeter = islandPerimeter(grid);
    cout<<"the perimeter is "<<perimeter;
    return 0;
}